package com.fingard.dsp.bank.directbank.alipay01;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.RefundState;
import com.fingard.dsp.bank.directbank.bankInterface.IRecRefund;
import com.fingard.dsp.bank.reqrespobj.recrefund.ReqQryRecRefund;
import com.fingard.dsp.bank.reqrespobj.recrefund.ReqRecRefund;
import com.fingard.dsp.bank.reqrespobj.recrefund.RetAtsQryRecRefund;
import com.fingard.dsp.bank.reqrespobj.recrefund.RetAtsRecRefund;
import com.fingard.text.StringHelper;
import net.sf.json.JSONObject;

import java.util.Date;


public class ALIPAY01RecRefund extends ALIPAY01Base implements IRecRefund {
	@Override
	public RetAtsRecRefund submitRecRefund(ReqRecRefund p_reqRef) throws Exception {
		RetAtsRecRefund retAts = new RetAtsRecRefund();
		retAts.oriRdSeq = p_reqRef.oriRdSeq;
		retAts.refundNo = p_reqRef.refundNo;
		
		try {
			logIsExist();
			
			ActSetItem actItem = this.getBankConfig().getActSetItem(p_reqRef.ownAct, "unifiedorder");
			if (actItem != null) {
                String signType = "RSA2";
                boolean useSignType = getBankConfig().getValueAsBool("useSignType");
                if (useSignType) {
                    signType = actItem.signType;
                }
				AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, 
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);
				
				AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
				
				JSONObject bizContent = new JSONObject();
				bizContent.put("out_trade_no", p_reqRef.oriRdSeq); 
//				bizContent.put("trade_no", p_reqRef.oriOppOrderNo); 
				bizContent.put("refund_amount", p_reqRef.amount); 
				bizContent.put("refund_currency", ""); 
				bizContent.put("refund_reason", p_reqRef.decription); 
				bizContent.put("out_request_no", p_reqRef.refundNo); 
				bizContent.put("operator_id", ""); 
				bizContent.put("store_id", ""); 
				bizContent.put("terminal_id", ""); 
				
				request.setBizContent(JSON.toJSONString(bizContent));
				
				WriteBankUrlLogLn(bankFront.serverURL);
				WriteBankLogStep2(request.getBizContent());
				
				AlipayTradeRefundResponse response = alipayClient.execute(request);
				WriteBankLogStep3(response.getBody());
				
				retAts.respCode = "0";
				retAts.respInfo = response.getMsg();
				if ("10000".equals(response.getCode())) {
					retAts.refundState = RefundState.REFUND_PAYING;
					retAts.oriOppOrderNo = response.getTradeNo();
					retAts.originalCode = response.getCode();
					retAts.originalInfo = response.getMsg();
					retAts.unifiedCode = getBankConfig().getMapValueByKey("recRefundMapping", retAts.originalCode);
				} else {
					retAts.respInfo = response.getSubMsg();
					retAts.refundState = RefundState.REFUND_FAIL;
					retAts.originalCode = response.getSubCode();
					retAts.originalInfo = retAts.respInfo;
					retAts.unifiedCode = getBankConfig().getMapValueByKey("recRefundMapping", retAts.originalCode);
				}
			} else {
				retAts.respCode = "0";
				retAts.respInfo = "未找到账号[" + p_reqRef.ownAct + "]商户配置信息!";
				retAts.refundState = RefundState.REFUND_FAIL;
				retAts.originalCode = "E9981";
				retAts.originalInfo = retAts.respInfo;
				retAts.unifiedCode = "E9981";
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}

	@Override
	public RetAtsQryRecRefund queryRecRefund(ReqQryRecRefund p_reqQryRef) throws Exception {
		RetAtsQryRecRefund retAts = new RetAtsQryRecRefund();
		retAts.oriRdSeq = p_reqQryRef.oriRdSeq;
		retAts.refundNo = p_reqQryRef.refundNo;
		
		try {
			logIsExist();
			
			ActSetItem actItem = this.getBankConfig().getActSetItem(p_reqQryRef.ownAct, "unifiedorder");
			if (actItem != null) {
                String signType = "RSA2";
                boolean useSignType = getBankConfig().getValueAsBool("useSignType");
                if (useSignType) {
                    signType = actItem.signType;
                }
				AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", actItem.appId,
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);
				
				JSONObject bizContent = new JSONObject();
//				bizContent.put("trade_no", p_reqQryRef.oriOppOrderNo);
				bizContent.put("out_trade_no", p_reqQryRef.oriRdSeq); 
				bizContent.put("out_request_no", p_reqQryRef.refundNo);
				
				AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
				request.setBizContent(JSON.toJSONString(bizContent));
				
				WriteBankUrlLogLn(bankFront.serverURL);
				WriteBankLogStep2(request.getBizContent());
				
				AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
				WriteBankLogStep3(response.getBody());
				
				retAts.respCode = "0";
				retAts.respInfo = response.getMsg();
				if ("10000".equals(response.getCode())) {
					if (StringHelper.hasAnyChar(response.getTradeNo())) {
						retAts.oriOppOrderNo = response.getTradeNo();
						retAts.refundState = RefundState.REFUND_SUCCESS;
					} else {
						retAts.refundState = RefundState.REFUND_PAYING;
					}
					
					String originalCode = response.getCode();
					String originalInfo = response.getMsg();
					if (StringHelper.hasAnyChar(response.getSubCode())) {
						originalCode = response.getSubCode();
						originalInfo = response.getSubMsg();
					}

					boolean useRefundSuccessDate = getBankConfig().getValueAsBool("useRefundSuccessDate");
					if (useRefundSuccessDate) {
                        Date refundDate = response.getGmtRefundPay();
                        if (refundDate != null) {
                            retAts.refundSuccessDate = Format.DateTimeFormat.format(refundDate);
                        }
                    }
					retAts.originalCode = originalCode;
					retAts.originalInfo = originalInfo;
					retAts.unifiedCode = getBankConfig().getMapValueByKey("recRefundMapping", originalCode);
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = response.getSubMsg();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_reqQryRef.ownAct + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}
}
